package org.zqy.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.zqy.util.HibernateTool;

/** 基本接口实现类，提供基础的增删改查 */
public class BaseDaoImpl {

	/** 保存 */
	public final static int SAVE = 0;
	/** 删除 */
	public final static int DELETE = 1;
	/** 修改 */
	public final static int UPDATE = 2;
	private Session session;

	/**
	 * 提供查询操作
	 * 
	 * @param hql
	 *            HQL语句
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List queryByHql(String hql) {
		List list = null;
		try {
			session = HibernateTool.getCurrentSession();
			session.beginTransaction();
			Query query = session.createQuery(hql);
			// 通过list对象获取结果,这个结果自动的封装成对应Domain对象
			list = query.list();
			session.getTransaction().commit();
		} catch (Exception e) {
			if (session.getTransaction() != null) {// 回滚事务
				session.getTransaction().rollback();
			}
			System.out.println(e.getMessage());
		} finally {
			// 关闭session
			if (session != null && session.isOpen())
				session.close();
		}
		return list;
	}

	/**
	 * 通用操作,提供增、删、改等操作
	 * 
	 * @param object
	 * @param type
	 *            <code>类型</code>
	 * @return
	 */
	public boolean CommonOpt(Object object, int type) {
		try {
			session = HibernateTool.getCurrentSession();
			session.beginTransaction();
			switch (type) {
			case SAVE:
				session.save(object);
				break;
			case DELETE:
				session.delete(object);
				break;
			case UPDATE:
				session.update(object);
				break;
			default:
				break;
			}
			session.getTransaction().commit();
		} catch (Exception e) {
			if (session.getTransaction() != null) {// 回滚事务
				session.getTransaction().rollback();
			}
			System.out.println(e.getMessage());
			return false;
		} finally {
			// 关闭session
			if (session != null && session.isOpen())
				session.close();
		}
		return true;
	}

}